﻿using MediatR;
using ProduceBasicData.Api.Application.Command.ProductionManage.Plan;
using ProduceBasicData.Api.DTO.ProductionManage;
using ProduceBasicData.Domain.ProductionManage;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.ProductionManage.Plan
{
    public class GetPlan_SchedulingByDateRangeCommandHandler : IRequestHandler<GetPlan_SchedulingByDateRangeCommand, ApiResult<List<Plandto>>>
    {
        private readonly IBaseRespository<Plan_Scheduling> planrepositry;

        public GetPlan_SchedulingByDateRangeCommandHandler(IBaseRespository<Plan_Scheduling> planrepositry)
        {
            this.planrepositry = planrepositry;
        }

        public Task<ApiResult<List<Plandto>>> Handle(GetPlan_SchedulingByDateRangeCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<List<Plandto>>()
            {
                Code = ApiEnum.Success,
                Msg = "获取排班信息成功"
            };

            try
            {
                // 解析日期字符串
                DateTime startDate = DateTime.ParseExact(request.StartDate, "yyyy-MM-dd", null);
                DateTime endDate = DateTime.ParseExact(request.EndDate, "yyyy-MM-dd", null);

                // 查询指定日期范围内的排班信息
                var info = from a in planrepositry.GetAll()
                           where a.UserId == request.UserId && !a.Isdel
                           && a.Date >= startDate && a.Date <= endDate.Date.AddDays(1).AddSeconds(-1) // 包含结束日期的全天
                           select new Plandto()
                           {
                               UserId = a.UserId,
                               Id = a.Id,
                               Type = a.Type,
                               Notes = a.Notes,
                               Date = a.Date.ToString("yyyy-MM-dd"),
                           };

                result.Data = info.ToList();
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Failed;
                result.Msg = "日期格式错误或查询失败：" + ex.Message;
                result.Data = new List<Plandto>();
            }

            return Task.FromResult(result);
        }
    }
}